package com.ruoyi.business.controller;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.ruoyi.business.domain.GoodsInfo;
import com.ruoyi.business.dto.ImprotGoodsDto;
import com.ruoyi.business.listener.GoodsInfoExcelListener;
import com.ruoyi.business.service.IGoodsInfoService;
import com.ruoyi.business.utils.BadRequestException;
import com.ruoyi.business.utils.CommonResult;
import com.ruoyi.business.utils.MyExcelUtil;
import com.ruoyi.business.utils.WeimobUtil;
import com.ruoyi.business.vo.BatchInsertGoodsVo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品信息Controller
 *
 * @author wyb
 * @date 2025-07-11
 */
@RestController
@RequestMapping("/business/goodsInfo")
public class GoodsInfoController extends BaseController {
    @Autowired
    private IGoodsInfoService goodsInfoService;

    @Autowired
    private WeimobUtil weimobUtil;

    /**
     * 查询商品信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:goodsInfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(GoodsInfo goodsInfo) {
        startPage();
        List<GoodsInfo> list = goodsInfoService.selectGoodsInfoList(goodsInfo);
        return getDataTable(list);
    }


    /**
     * 获取商品信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:goodsInfo:query')")
    @GetMapping(value = "/{skuBarCode}")
    public AjaxResult getInfo(@PathVariable("skuBarCode") String skuBarCode) {
        return success(goodsInfoService.selectGoodsInfoBySkuBarCode(skuBarCode));
    }

    /**
     * 新增商品信息
     */
    @PreAuthorize("@ss.hasPermi('business:goodsInfo:add')")
    @Log(title = "商品信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody GoodsInfo goodsInfo) {
        return toAjax(goodsInfoService.insertGoodsInfo(goodsInfo));
    }

    /**
     * 修改商品信息
     */
    @PreAuthorize("@ss.hasPermi('business:goodsInfo:edit')")
    @Log(title = "商品信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GoodsInfo goodsInfo) {
        return toAjax(goodsInfoService.updateGoodsInfo(goodsInfo));
    }

    /**
     * 删除商品信息
     */
    @PreAuthorize("@ss.hasPermi('business:goodsInfo:remove')")
    @Log(title = "商品信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{skuBarCodes}")
    public AjaxResult remove(@PathVariable String[] skuBarCodes) {
        return toAjax(goodsInfoService.deleteGoodsInfoBySkuBarCodes(skuBarCodes));
    }


    /**
     * 导出商品信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:goodsInfo:export')")
    @Log(title = "商品信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, GoodsInfo goodsInfo) {
        List<GoodsInfo> list = goodsInfoService.selectGoodsInfoList(goodsInfo);
        ExcelUtil<GoodsInfo> util = new ExcelUtil<GoodsInfo>(GoodsInfo.class);
        util.exportExcel(response, list, "商品信息");
    }

    /**
     * 导入excel商品信息
     *
     * @param file
     * @return
     */
    @PreAuthorize("@ss.hasPermi('business:goodsInfo:import')")
    @Log(title = "商品信息", businessType = BusinessType.IMPORT)
    @PostMapping("/importGoodsInfoFile")
    @ResponseBody
    public CommonResult importBuyerInfoFile(@RequestParam("file") MultipartFile file) throws IOException {
        GoodsInfoExcelListener listener = new GoodsInfoExcelListener(goodsInfoService);
        EasyExcel.read(file.getInputStream(), listener)
                .sheet()
                .headRowNumber(1)
                .doRead();
        List<String> errorList = listener.errorList;
        if (CollUtil.isNotEmpty(errorList)) {
            return CommonResult.failed("导入失败,请检查," + listener.errorList);
        } else {
            return CommonResult.success(null);
        }
    }

    /*商品下载模板
     * */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<ImprotGoodsDto> util = new ExcelUtil<ImprotGoodsDto>(ImprotGoodsDto.class);
        // 获取数据字典列表
        List<SysDictData> goodsCategoryList = DictUtils.getDictCache("sys_goods_category");
        // 物流公司名称集合
        List<String> logisticsCompanyLabels = goodsCategoryList.stream().map(SysDictData::getDictLabel).collect(Collectors.toList());
        // 生成包含数据验证的模板
        try (ExcelWriter excelWriter = MyExcelUtil.getExcelWriter(response.getOutputStream())) {
            // 创建工作表
            WriteSheet writeSheet = EasyExcel.writerSheet("Sheet1").head(ImprotGoodsDto.class).build();
            // 先写入空数据以初始化Sheet
            excelWriter.write(new ArrayList<>(), writeSheet);
            // 获取实际的Sheet对象
            Sheet sheet = excelWriter.writeContext().writeSheetHolder().getSheet();
            // 添加数据验证
            DataValidationHelper helper = sheet.getDataValidationHelper();
            DataValidationConstraint constraint = helper.createExplicitListConstraint(logisticsCompanyLabels.toArray(new String[0]));
            // 假设要在第4列添加数据字典下拉框
            CellRangeAddressList addressList = new CellRangeAddressList(1, 1000, 8, 8); // 行,行,列,列
            DataValidation validation = helper.createValidation(constraint, addressList);
            sheet.addValidationData(validation);
            excelWriter.write(new ArrayList<>(), writeSheet);
        } catch (IOException e) {
            e.printStackTrace();
        }

        util.importTemplateExcel(response, "商品数据");
    }

    /*1.查询在售商品详情接口
     * */
    @GetMapping("/selectGoodsByWm/{goodsId}")
    public List<GoodsInfo> selectGoodsByWm(@PathVariable("goodsId") Long goodsId) throws Exception {
        List<GoodsInfo> goodsInfoList = weimobUtil.selectGoodListfetchFromWeimob(goodsId);
        return goodsInfoList;
    }

    @PreAuthorize("@ss.hasPermi('business:goodsInfo:batchInsertGoodsByWm')")
    @PostMapping("/batchInsertGoodsByWm")
    public AjaxResult batchInsertGoodsByWm(@RequestBody List<Long> goodsIdList) throws Exception {
        if (CollectionUtils.isEmpty(goodsIdList)) {
            throw new BadRequestException("商品编号不能为空！");
        }
        if (goodsIdList.size() > 20) {
            throw new BadRequestException("一次最多支持查询 20 条商品编号");
        }
        List<GoodsInfo> goodsInfos = new ArrayList<>();
        for (Long goodId:goodsIdList) {
            List<GoodsInfo> goods = this.selectGoodsByWm(goodId);
            goodsInfoService.batchInsert(goods);
        }
        return AjaxResult.success("插入商品成功");
    }
}
